package com.txh.blog.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.txh.blog.consts.Consts;
import com.txh.blog.mapper.LabelMapper;
import com.txh.blog.model.Label;
import com.txh.blog.service.LabelService;
import com.txh.blog.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LabelServiceImpl implements LabelService {

    @Autowired
    private LabelMapper labelMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public Map<String, Object> getLabelList(Integer pageNum, Integer pageSize) {
        Map<String,Object> page = new HashMap<>();
        int total = labelMapper.getLabelTotal();
        pageNum =pageNum==null?1:pageNum;
        pageSize =pageSize==null?10:pageSize;
        List<Label> list = labelMapper.getLabelPage((pageNum-1)*pageSize,pageSize);
        page.put("total",total);
        page.put("list",list);
        page.put("curr",pageNum);
        return page;
    }

    @Override
    public void deleteLabelById(Long id) {
        labelMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void addLabel(Label label) {
        redisService.del(Consts.LABELS_CACHE);
        labelMapper.insert(label);
    }

    @Override
    public List<Label> allLabels() {
        List<Label> labels = labelMapper.selectAll();
        redisService.set(Consts.LABELS_CACHE,JSONObject.toJSONString(labels),100);
        return labels;
    }
}
